package com.js.data.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.js.data.common.config.RsaProperties;
import com.js.data.common.constant.SymbolConstant;
import com.js.data.common.dto.SecurityUserDTO;
import com.js.data.common.exception.ApiException;
import com.js.data.common.utils.RsaUtils;
import com.js.data.common.utils.SecurityUtils;
import com.js.data.common.utils.StringUtils;
import com.js.data.system.dto.BatchUserPermDTO;
import com.js.data.system.dto.PasswordDTO;
import com.js.data.system.dto.UserDTO;
import com.js.data.system.dto.UserOrgPermDTO;
import com.js.data.system.entity.SysUser;
import com.js.data.system.mapper.SysDeptMapper;
import com.js.data.system.mapper.SysUserMapper;
import com.js.data.system.query.UserQuery;
import com.js.data.system.service.UserDeptService;
import com.js.data.system.service.UserRoleService;
import com.js.data.system.service.UserService;
import com.js.data.system.vo.SimpleRoleVO;
import com.js.data.system.vo.UserPageVO;
import com.js.data.system.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author wujj
 * @since 2022-09-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements UserService {


    private final static String DEFAULT_PASSWORD = "ab123456";

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private UserDeptService userDeptService;

    @Resource
    private SysDeptMapper sysDeptMapper;

    /**
     * 用户分页
     *
     * @param query 查询条件
     * @return IPage<UserPageVO>
     */
    @Override
    public IPage<UserPageVO> pageUser(UserQuery query) {
        Long deptId = query.getDeptId();
        Page<UserPageVO> page = new Page<>(query.getCurrent(), query.getSize());

        SecurityUserDTO currentUserInfo = SecurityUtils.getCurrentUserInfo();
        if (Objects.isNull(deptId) || deptId == 0) {
            // 非管理员情况
            if (!currentUserInfo.isAdmin()) {
                // 用户数据权限  0-全部 1-本人 2-本部门 3-本部门及下级部门 4-指定
                String permType = currentUserInfo.getPermType();
                if (SymbolConstant.ONE_STR.equals(permType)) {
                    query.setUserId(currentUserInfo.getId());
                } else {
                    List<Long> deptIds = SecurityUtils.getCurrentUserDataScope();
                    query.setDeptIds(deptIds);
                }
            }
        } else {
            if (!currentUserInfo.isAdmin()) {
                //  1-本人 2-本部门 情况下都要特殊处理下
                String permType = currentUserInfo.getPermType();
                if (SymbolConstant.ONE_STR.equals(permType)) {
                    query.setUserId(currentUserInfo.getId());
                } else {
                    List<Long> deptIds = SecurityUtils.getCurrentUserDataScope();
                    query.setDeptIds(deptIds);
                }
            } else {
                List<Long> deptIds = sysDeptMapper.selectAllChildIdByPid(deptId);
                deptIds.add(deptId);
                query.setDeptIds(deptIds);
            }
        }
        return getBaseMapper().selectPageVO(page, query);
    }

    /**
     * 保存用户
     *
     * @param userDTO 用户表单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(UserDTO userDTO) {
        insertUserExistCheck(userDTO);
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDTO, user);
        user.setPassword(passwordEncoder.encode(DEFAULT_PASSWORD));
        UserOrgPermDTO userPerm = userDTO.getUserPerm();
        String type = userPerm.getType();
        user.setPermType(type);
        if(userDTO.getRoleIds().contains(SymbolConstant.ONE_INT)){
            user.setAdminFlag(SymbolConstant.ONE_STR);
        }else{
            user.setAdminFlag(SymbolConstant.ZERO_STR);
        }
        save(user);
        Long userId = user.getId();
        // 用户角色
        userRoleService.saveBatchToDB(userDTO.getRoleIds(), userId);
        // 用户数据权限
        if (type.equals(SymbolConstant.FOUR_STR)) {
            userDeptService.saveBatchToDB(userPerm.getDeptIds(), userId);
        }
    }

    /**
     * 修改用户
     *
     * @param id      用户uid
     * @param userDTO 用户表单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editUser(Long id, UserDTO userDTO) {
        String oldPermType = editUserCheck(id, userDTO);
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDTO, user);
        user.setId(id);
        UserOrgPermDTO userPerm = userDTO.getUserPerm();
        user.setPermType(userPerm.getType());
        if(userDTO.getRoleIds().contains(SymbolConstant.ONE_INT)){
            user.setAdminFlag(SymbolConstant.ONE_STR);
        }else{
            user.setAdminFlag(SymbolConstant.ZERO_STR);
        }
        updateById(user);
        // 用户角色
        userRoleService.removeByUserId(id);
        userRoleService.saveBatchToDB(userDTO.getRoleIds(), id);
        // 用户数据权限
        if (oldPermType.equals(SymbolConstant.FOUR_STR)) {
            userDeptService.removeByUserId(id);
        }
        if (userPerm.getType().equals(SymbolConstant.FOUR_STR)) {
            userDeptService.saveBatchToDB(userPerm.getDeptIds(), id);
        }
    }

    /**
     * 删除用户
     *
     * @param id 用户id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long id) {
        // admin用户不能删除
        SysUser sysUser = getById(id);
        Optional.ofNullable(sysUser).orElseThrow(() -> new ApiException("用户不存在"));
        if (sysUser.getAdminFlag().equals(SymbolConstant.ONE_STR)) {
            throw new ApiException("管理员不能删除");
        }
        removeById(id);
        // 删除用户角色
        userRoleService.removeByUserId(id);
        // 删除用户部门
        userDeptService.removeByUserId(id);
    }

    /**
     * 获取用户详情
     *
     * @param id 用户id
     * @return UserVO
     */
    @Override
    public UserVO getUser(Long id) {
        SysUser sysUserEX = getById(id);
        Optional.ofNullable(sysUserEX).orElseThrow(() -> new ApiException("用户不存在"));
        UserVO userDetailVO = new UserVO();
        BeanUtils.copyProperties(sysUserEX, userDetailVO);
        // 获取用户角色
        List<SimpleRoleVO> userRoleList = userRoleService.listUserRoleByUid(id);
        userDetailVO.setUserRoleList(userRoleList);
        // 获取用户数据权限
        // 数据权限 0-全部 1-本人 2-本部门 3-本部门及下级部门 4-指定
        UserOrgPermDTO userPerm = new UserOrgPermDTO();
        String permType = sysUserEX.getPermType();
        userPerm.setType(permType);
        if (permType.equals(SymbolConstant.FOUR_STR)) {
            // 从sys_user_dept获取数据
            List<Long> deptIds = userDeptService.getAssignDeptIds(id);
            userPerm.setDeptIds(deptIds);
        }
        userDetailVO.setUserPerm(userPerm);
        return userDetailVO;
    }

    /**
     * 启用用户
     *
     * @param id 用户id
     */
    @Override
    public void stateUser(Long id) {
        SysUser sysUser = getById(id);
        Optional.ofNullable(sysUser).orElseThrow(() -> new ApiException("用户不存在"));
        String oldState = sysUser.getState();
        if (oldState.equals(SymbolConstant.ZERO_STR)) {
            sysUser.setState(SymbolConstant.ONE_STR);
        }
        if (oldState.equals(SymbolConstant.ONE_STR)) {
            sysUser.setState(SymbolConstant.ZERO_STR);
        }
        updateById(sysUser);
    }

    /**
     * 根据登录名获取用户登录信息
     *
     * @param username 用户名
     * @return SecurityUserDTO
     */
    @Override
    public SecurityUserDTO getUserByUserName(String username) {
        SysUser sysUser = getByUsername(username);
        Optional.ofNullable(sysUser).orElseThrow(() -> new ApiException("用户不存在"));
        SecurityUserDTO securityUserDTO = new SecurityUserDTO();
        securityUserDTO.setId(sysUser.getId());
        securityUserDTO.setEnabled(sysUser.getState().equals(SymbolConstant.ONE_STR));
        securityUserDTO.setPassword(sysUser.getPassword());
        securityUserDTO.setUsername(sysUser.getUserName());
        securityUserDTO.setNickName(sysUser.getNickName());
        securityUserDTO.setDeptId(sysUser.getDeptId());
        securityUserDTO.setDeptName(sysUser.getDeptName());
        securityUserDTO.setAdmin(sysUser.getAdminFlag().equals(SymbolConstant.ONE_STR));
        securityUserDTO.setPermType(sysUser.getPermType());
        return securityUserDTO;
    }

    /**
     * 用户修改密码
     *
     * @param passwordDTO 表单
     */
    @Override
    public void resetPassword(PasswordDTO passwordDTO) {
        //校验数据是否存在
        // 密码解密
        String password;
        try {
            password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passwordDTO.getPassword());
        } catch (Exception e) {
            throw new ApiException("解密错误");
        }
        SysUser sysUserEX = getById(passwordDTO.getId());
        Optional.ofNullable(sysUserEX).orElseThrow(() -> new ApiException("用户不存在"));
        if (passwordEncoder.matches(password, sysUserEX.getPassword())) {
            throw new ApiException("新密码与原密码相同");
        }

        SysUser user = new SysUser();
        user.setId(passwordDTO.getId());
        //密码加密
        String encodePassword = passwordEncoder.encode(password);
        user.setPassword(encodePassword);
        updateById(user);
    }

    /**
     * 批量修改用户角色权限
     *
     * @param batchUserPermDTO 批量用户数据权限修改表单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUserRolePerm(BatchUserPermDTO batchUserPermDTO) {
        List<Long> roleIdList = batchUserPermDTO.getRoleIdList();
        if (CollectionUtil.isEmpty(roleIdList)) {
            throw new ApiException("角色列表为空");
        }
        List<Long> uidList = batchUserPermDTO.getUidList();
        userRoleService.removeByUserIds(uidList);
        uidList.forEach(uid -> userRoleService.saveBatchToDB(roleIdList, uid));
    }

    /**
     * 批量删除用户
     *
     * @param batchUserPermDTO 批量用户数据权限修改表单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteUser(BatchUserPermDTO batchUserPermDTO) {
        List<Long> uidList = batchUserPermDTO.getUidList();
        listByIds(uidList).forEach(user -> {
            if (user.getAdminFlag().equals(SymbolConstant.ONE_STR)) {
                throw new ApiException("管理员不能删除");
            }
        });
        removeBatchByIds(uidList);
        // 删除用户角色
        userRoleService.removeByUserIds(uidList);
        // 删除用户部门
        userDeptService.removeByUserIds(uidList);
    }

    /**
     * 批量修改用户部门数据权限
     *
     * @param batchUserPermDTO 批量用户数据权限修改表单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUserDeptPerm(BatchUserPermDTO batchUserPermDTO) {
        UserOrgPermDTO userPerm = batchUserPermDTO.getUserPerm();
        Optional.ofNullable(userPerm).orElseThrow(() -> new ApiException("数据权限为空"));
        List<Long> uidList = batchUserPermDTO.getUidList();
        // 用户数据权限
        userDeptService.removeByUserIds(uidList);
        String type = userPerm.getType();
        List<SysUser> batchList = new ArrayList<>();
        uidList.forEach(id -> {
            SysUser sysUser = new SysUser();
            sysUser.setId(id);
            sysUser.setPermType(type);
            batchList.add(sysUser);
            if (type.equals(SymbolConstant.FOUR_STR)) {
                userDeptService.saveBatchToDB(userPerm.getDeptIds(), id);
            }
        });
        updateBatchById(batchList);

    }


    /**
     * 新增检查用户是否存在
     *
     * @param userDTO 用户表单
     */
    private void insertUserExistCheck(UserDTO userDTO) {
        SysUser user = getByUsername(userDTO.getUserName());
        if (user != null) {
            throw new ApiException("用户名已存在");
        }
        if (StringUtils.isNoneBlank(userDTO.getPhone())) {
            user = getByPhone(userDTO.getPhone());
            if (user != null) {
                throw new ApiException("用户电话已存在");
            }
        }
        if (StringUtils.isNoneBlank(userDTO.getEmail())) {
            user = getByEmail(userDTO.getEmail());
            if (user != null) {
                throw new ApiException("用户邮箱已存在");
            }
        }

    }

    /**
     * 修改检查用户
     *
     * @param id      用户uid
     * @param userDTO 表单
     */
    private String editUserCheck(Long id, UserDTO userDTO) {
        SysUser userExist = getById(id);
        Optional.ofNullable(userExist).orElseThrow(() -> new ApiException("用户不存在"));
        SysUser user1 = getByUsername(userDTO.getUserName());
        if (user1 != null && !userExist.getId().equals(user1.getId())) {
            throw new ApiException("用户名已存在");
        }
        if (StringUtils.isNoneBlank(userDTO.getEmail())) {
            SysUser user2 = getByEmail(userDTO.getEmail());
            if (user2 != null && !userExist.getId().equals(user2.getId())) {
                throw new ApiException("用户电话已存在");
            }
        }
        if (StringUtils.isNoneBlank(userDTO.getPhone())) {
            SysUser user3 = getByPhone(userDTO.getPhone());
            if (user3 != null && !userExist.getId().equals(user3.getId())) {
                throw new ApiException("用户邮箱已存在");
            }
        }
        return userExist.getPermType();
    }

    private SysUser getByUsername(String userName) {
        return lambdaQuery().eq(SysUser::getUserName, userName).one();
    }


    private SysUser getByPhone(String phone) {
        return lambdaQuery().eq(SysUser::getPhone, phone).one();
    }

    private SysUser getByEmail(String email) {
        return lambdaQuery().eq(SysUser::getEmail, email).one();
    }
}
